from tortoise import fields

from apps.models.base_model import BaseModel
from apps.utils import get_password_hash
from apps.utils.enumerate import StateEnum, UserTypeEnum


class User(BaseModel):
    __doc__ = "用户表"
    account = fields.CharField(max_length=32, null=False, description="用户账号", unique=True)
    password = fields.CharField(max_length=128, null=False, description="密码")
    mobile = fields.CharField(max_length=32, null=True, description="手机号")
    email = fields.CharField(max_length=256, null=True, description="邮箱")
    is_admin = fields.BooleanField(default=False, description="是否管理员")
    state = fields.IntEnumField(StateEnum, default=StateEnum.allow, description="允许登录的权限,1:允许,2:禁用")
    user_type = fields.IntEnumField(UserTypeEnum, default=UserTypeEnum.user, description='用户类型，1:普通用户 2:管理员')

    class Meta:
        table = "user"
        table_description = "用户表"

    @classmethod
    async def create(cls, password, **kwargs):
        """
        自定义创建 密码加密
        :param password:
        :param kwargs:
        :return:
        """
        if not password:
            raise ValueError("密码为空！")

        password = get_password_hash(password)
        user = User(password=password, **kwargs)
        await user.save(force_create=True)
        return user
